<template>
  <div>
    <el-select :value="c1 || c1$" :disabled="$disabled" @change="handleLv1Change">
      <el-option v-for="item in lv1" :label="item.class1" :value="item.class1" :key="item.class1">
        {{item.class1}}
      </el-option>
    </el-select>
    <el-select :value="c2 || c2$" @change="handleLv2Change" :disabled="$disabled">
      <el-option v-for="item in lv2" :label="item.class2" :value="item.class2" :key="item.class2">
        {{item.class2}}
      </el-option>
    </el-select>
    <el-select v-if="!$hideLv4" :disabled="$disabled" :value="c4 || c4$" @change="handleLv4Change">
      <el-option v-for="item in lv4" :label="item" :value="item" :key="item">
        {{item}}
      </el-option>
    </el-select>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex'
  export default {
    name: 'pro-cascader',
    props: {
      hideLv4: Boolean,
      disabled: Boolean,
      c1: {
        type: String,
        default: ''
      },
      c2: {
        type: String,
        default: ''
      },
      c4: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        c1$: '',
        c2$: '',
        c4$: ''
      }
    },
    computed: {
      ...mapState('ci', {
        lv4: state => state.lv4IDs,
        lv1: state => state.lv1,
        lv2Obj: state => state.lv2
      }),
      $hideLv4 () {
        return this.hideLv4 === '' || this.hideLv4
      },
      $disabled () {
        return this.disabled === '' || this.disabled
      },
      lv2 () {
        return this.lv2Obj[this.c1$]
      }
    },
    methods: {
      /* 获取各级目录 */
      ...mapActions('ci', ['fetchLv4', 'fetchLv1', 'fetchLv2']),
      /* lv4(3)值发生变化 */
      handleLv4Change (v) {
        this.$emit('update:c4', v)
        this.$emit('lv4-change', v)
        this.c4$ = v
      },
      handleLv2Change (v) {
        this.$emit('update:c2', v)
        this.$emit('lv2-change', v)
        this.c2$ = v
      },
      handleLv1Change (v) {
        this.$emit('update:c1', v)
        this.$emit('lv1-change', v)
        this.c1$ = v
      }
    },
    watch: {
      /* watch c1,当c1变化，重置c2，lv2 */
      c1$ (v) {
        this.fetchLv2({ c1: this.c1$ })
        this.handleLv2Change('')
      },
      /* watch c2，当c2变化，重置c4，lv4 */
      c2$ (v) {
        if (this.$hideLv4) return
        this.fetchLv4({ c2: this.c2$ })
        this.handleLv4Change('')
      }
    },
    created () {
      this.fetchLv1()
    }
  }
</script>

<style lang="scss" scoped>

</style>
